﻿namespace ElegantRoute.Routing {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Routing;
    using System.Text;

    public class ElegantRoute : Route {
        
        public static readonly string[] ToElegant =  new [] { "controller", "action" };

        public ElegantRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler)
            : base(url, defaults, constraints, dataTokens, routeHandler) { }

        public override RouteData GetRouteData(HttpContextBase httpContext) {
            var result = base.GetRouteData(httpContext);
            if (result == null) return null;

            foreach (var key in ToElegant)
                HandleItem(result.Values, key, StringElegantHelper.DeElegant);
            return result;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) {
            var elegantValues = new RouteValueDictionary(values);
            foreach (var key in ToElegant)
                HandleItem(elegantValues, key, StringElegantHelper.Elegant);
            return base.GetVirtualPath(requestContext, elegantValues);
        }

        private void HandleItem(RouteValueDictionary dict, string key, Func<string, string> handler) {
            if (!dict.ContainsKey(key)) return;
            //
            var value = dict[key];
            if (!(value is string)) return;
            //
            dict[key] = handler(value as string);
        }

    }
}